package com.zhn.usermanager.util;

import okhttp3.*;

import java.io.IOException;

/**
 * @author thinknovo   Okhttp3是一个移动端的第三方服务请求工具，此工具必须以异步请求的行为完成，所以需要手动创建线程再进行调用
 *                     如果在请求服务时，没有以异步线程方式请求，那么服务将被阻断(为了避免主线程被锁死的风险)
 * @version 1.0        添加okhttp驱动包
 */
public class OkhttpClient {
    public static void main(String[] args) {
//        String s = okhttpGet("http://apis.juhe.cn/simpleWeather/query?city=%E6%88%90%E9%83%BD&key=d5f452d52936d728bae5b0eaaf41493e");
//        System.out.println(s);

        okhttpPost();
    }

    public static String okhttpGet(String url) {
        String[] result = new String[]{""};
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        final Call call = okHttpClient.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    result[0] = response.body().string();
                    System.out.println(result[0]);   // 得到返回的json
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return result[0];
    }

    public static String okhttpPost() {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("city", "北京")
                .add("key", "d5f452d52936d728bae5b0eaaf41493e")
                .build();
        Request request = new Request.Builder()
                .url("http://apis.juhe.cn/simpleWeather/query")
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("e.getMessage()=" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("response.protocol()=" + response.protocol() + " response.code()=" + response.code() + " response.message()=" + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    System.out.println("header param=" + headers.name(i) + ":" + headers.value(i));
                }
                System.out.println(response.body().string());
            }
        });
        return "";
    }
}
